package listeners0708; /***
 * Excerpted from "The Definitive ANTLR 4 Reference",
 * published by The Pragmatic Bookshelf.
 * Copyrights apply to this code. It may not be used to create training material, 
 * courses, books, articles, and the like. Contact us if you are in doubt.
 * We make no guarantees that this code is fit for any purpose. 
 * Visit http://www.pragmaticprogrammer.com/titles/tpantlr2 for more book information.
 ***/

import antlr4demo.listeners0708.demo010704.Demo01ExprBaseListener;
import antlr4demo.listeners0708.demo010704.Demo01ExprLexer;
import antlr4demo.listeners0708.demo010704.Demo01ExprParser;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.TerminalNode;

import java.io.FileInputStream;
import java.io.InputStream;

public class TestExprEmitter {
    /**
     * Sample "emitter"
     */
    public static class LeafListener extends Demo01ExprBaseListener {
        public void visitTerminal(TerminalNode node) {
            System.out.println(node.getText());
        }
    }

    /**
     * Sample "emitter" that relies on order of enter/exit.
     * 1+2*3 => (1+(2*3))
     */
    public static class Printer extends Demo01ExprBaseListener {
        public void enterE(Demo01ExprParser.EContext ctx) {
            if (ctx.getChildCount() > 1) System.out.print("(");
        }

        public void exitE(Demo01ExprParser.EContext ctx) {
            if (ctx.getChildCount() > 1) System.out.print(")");
        }

        public void visitTerminal(TerminalNode node) {
            System.out.print(node.getText());
        }
    }

    public static void main(String[] args) throws Exception {
        String inputFile = null;
        if (args.length > 0) inputFile = args[0];
        InputStream is = System.in;
        if (inputFile != null) is = new FileInputStream(inputFile);
        ANTLRInputStream input = new ANTLRInputStream(is);
        Demo01ExprLexer lexer = new Demo01ExprLexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        Demo01ExprParser parser = new Demo01ExprParser(tokens);
        ParseTree tree = parser.s(); // parse
        // show tree in text form
        System.out.println(tree.toStringTree(parser));

        ParseTreeWalker walker = new ParseTreeWalker();
        walker.walk(new LeafListener(), tree);

        walker.walk(new Printer(), tree);
        System.out.println();
    }
}
